 /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package View;

import View.Model.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

import org.json.JSONObject;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 *
 * @author ANA
 */
public class MainPage extends javax.swing.JFrame {

    /**
     * Creates new form MainPage
     */
    public Project project = new Project();
    public Topic topic = new Topic();
    public Server server = new Server();
    public Protocol protocol = new Protocol();
    public Thing thing = new Thing();

    public MainPage() {
        initComponents();
        this.insereActions((DefaultMutableTreeNode)this.arvoreCoisa.getModel().getRoot(),this.project);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        desktopPane = new javax.swing.JDesktopPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        arvoreCoisa = new javax.swing.JTree();
        menuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();

        openMenuItem = new javax.swing.JMenuItem();
        openProjectMenuItem = new javax.swing.JMenuItem();
        saveAsMenuItem = new javax.swing.JMenuItem();
        serverMenuItem = new javax.swing.JMenuItem();
        topicMenuItem = new javax.swing.JMenuItem();
        protocolPage = new javax.swing.JMenuItem();
        exitMenuItem = new javax.swing.JMenuItem();
        projectMenu = new javax.swing.JMenu();
        componentMenuItem = new javax.swing.JMenuItem();
        portMenuItem = new javax.swing.JMenuItem();
        controllerMenuItem = new javax.swing.JMenuItem();
        thingMenuItem = new javax.swing.JMenuItem();
        helpMenu = new javax.swing.JMenu();
        contentMenuItem = new javax.swing.JMenuItem();
        aboutMenuItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jScrollPane1.setViewportView(arvoreCoisa);

        desktopPane.add(jScrollPane1);
        jScrollPane1.setBounds(0, 0, 210, 350);

        fileMenu.setMnemonic('f');
        fileMenu.setText("File");
        fileMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileMenuActionPerformed(evt);
            }
        });

        openMenuItem.setMnemonic('o');
        openMenuItem.setText("New Project");
        openMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(openMenuItem);

        openProjectMenuItem.setText("Open Project");
        openProjectMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openProjectMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(openProjectMenuItem);

        saveAsMenuItem.setMnemonic('a');
        saveAsMenuItem.setText("Save");
        saveAsMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveAsMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(saveAsMenuItem);


        exitMenuItem.setMnemonic('x');
        exitMenuItem.setText("Exit");
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        projectMenu.setMnemonic('e');
        projectMenu.setText("Project");

        serverMenuItem.setMnemonic('s');
        serverMenuItem.setText("Server");
        serverMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                serverMenuItemActionPerformed(evt);
            }
        });
        projectMenu.add(serverMenuItem);

        protocolPage.setText("Protocol");
        protocolPage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                protocolPageActionPerformed(evt);
            }
        });
        projectMenu.add(protocolPage);

        topicMenuItem.setText("Topic");
        topicMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                topicMenuItemActionPerformed(evt);
            }
        });
        projectMenu.add(topicMenuItem);

        componentMenuItem.setMnemonic('c');
        componentMenuItem.setText("Component");
        componentMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                componentMenuItemActionPerformed(evt);
            }
        });
        projectMenu.add(componentMenuItem);

        portMenuItem.setMnemonic('p');
        portMenuItem.setText("Port");
        portMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                portMenuItemActionPerformed(evt);
            }
        });
        projectMenu.add(portMenuItem);

        controllerMenuItem.setMnemonic('c');
        controllerMenuItem.setText("Controller");
        controllerMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                controllerMenuItemActionPerformed(evt);
            }
        });
        projectMenu.add(controllerMenuItem);

        thingMenuItem.setMnemonic('t');
        thingMenuItem.setText("Thing");
        thingMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
               thingMenuItemActionPerformed(evt);
            }
        });
        projectMenu.add(thingMenuItem);
        menuBar.add(projectMenu);

        helpMenu.setMnemonic('h');
        helpMenu.setText("Help");

        contentMenuItem.setMnemonic('c');
        contentMenuItem.setText("Contents");
        helpMenu.add(contentMenuItem);

        aboutMenuItem.setMnemonic('a');
        aboutMenuItem.setText("About");
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        setJMenuBar(menuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(desktopPane, javax.swing.GroupLayout.DEFAULT_SIZE, 594, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(desktopPane, javax.swing.GroupLayout.PREFERRED_SIZE, 354, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitMenuItemActionPerformed

    private void fileMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_fileMenuActionPerformed

    private void openMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openMenuItemActionPerformed
        // TODO add your handling code here:
        NewProject tela = new NewProject(arvoreCoisa, project, thing);
        tela.setVisible(true);
    }//GEN-LAST:event_openMenuItemActionPerformed

    private void serverMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
        ServerPage tela = new ServerPage(project);
        tela.setVisible(true);
    }                                              

    private void componentMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
        ComponentPage tela = new ComponentPage(arvoreCoisa, project);
        tela.setVisible(true);
    }                                              

    private void portMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
        PortPage tela = new PortPage();
        tela.setVisible(true);
    }                                              

    private void controllerMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_serverMenuItemActionPerformed
        // TODO add your handling code here:
        ControllerPage tela = new ControllerPage();
        tela.setVisible(true);
    }//GEN-LAST:event_serverMenuItemActionPerformed

    
    private void thingMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
        ThingPage tela = new ThingPage();
        tela.setVisible(true);
    }             
    

    private void openProjectMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openProjectMenuItemActionPerformed
        // TODO add your handling code here:
        OpenProject tela = new OpenProject(project, arvoreCoisa);
        tela.setVisible(true);
        /*String aux = project.getProjectFolder() + "project.json";
        String conteudo = "";
        try {
            conteudo = new String(Files.readAllBytes(Paths.get(aux)));
        } catch (IOException ex) {
            Logger.getLogger(ServerPage.class.getName()).log(Level.SEVERE, null, ex);
        }
        JSONObject objetoJson = new JSONObject(conteudo);
        
   
        //JSONObject objetoJson = jsonArray.getJSONObject(x);
            
        project.setNomeServer(objetoJson.getString("nomeServer"));
        project.setPasswordServer(objetoJson.getString("passwordServer"));
        project.setIdServer(objetoJson.getString("idServer"));
        project.setPortaServer(objetoJson.getString("portaServer"));*/
        
    }//GEN-LAST:event_openProjectMenuItemActionPerformed

    private void saveAsMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveAsMenuItemActionPerformed
        // TODO add your handling code here:

        String projectFolder = project.getProjectFolder();
        String projectName = project.getProjectNome();
        String projectPath = projectFolder + File.separator + projectName + File.separator;

        ObjectMapper mapper = new ObjectMapper();

        try {
            mapper.writerWithDefaultPrettyPrinter().writeValue(Paths.get(String.format("%s%s.json",projectPath,projectName)).toFile(), project);
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_saveAsMenuItemActionPerformed

    private void protocolPageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_protocolPageActionPerformed
        // TODO add your handling code here:
        ProtocolPage tela = new ProtocolPage(project);
        tela.setVisible(true);
    }//GEN-LAST:event_protocolPageActionPerformed

    private void topicMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_topicMenuItemActionPerformed
        // TODO add your handling code here:
        TopicPage tela = new TopicPage(topic, arvoreCoisa, project);
        tela.setVisible(true);
    }//GEN-LAST:event_topicMenuItemActionPerformed

     public void insereActions(DefaultMutableTreeNode rootNode, Project novoProject){
        DefaultTreeModel treeModel = (DefaultTreeModel)arvoreCoisa.getModel();
        treeModel.setRoot(rootNode);
        arvoreCoisa.addMouseListener(new MouseAdapter(){
            public void mouseClicked(MouseEvent me) {
                JPopupMenu popupMenu = new JPopupMenu();
                JMenuItem createNewThing = new JMenuItem("Create new Thing");
                JMenuItem createNewComponent = new JMenuItem("Create new component");
                JMenuItem createNewController = new JMenuItem("Create new controller");
                JMenuItem createNewTopic = new JMenuItem("Create new Topic");
                JMenuItem createNewPort = new JMenuItem("Create new Port");
                JMenuItem editProtocol = new JMenuItem("Edit Protocol");
                JMenuItem editServer = new JMenuItem("Edit Server");
                TreePath tp = arvoreCoisa.getPathForLocation(me.getX(), me.getY());
                String [] value = tp.getLastPathComponent().toString().split(" ");
                arvoreCoisa.remove(popupMenu);
                arvoreCoisa.setComponentPopupMenu(popupMenu);
                if(SwingUtilities.isRightMouseButton(me)){
                    createNewComponent.removeAll();
                    createNewController.removeAll();
                    createNewThing.removeAll();
                    TipoObjeto myObjeto = TipoObjeto.valueOf(value[0].replaceAll("[<,>]*","").trim().toUpperCase());
                    switch (myObjeto) {
                        case THING:
                            createNewComponent.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) arvoreCoisa.getLastSelectedPathComponent();
                                    if (novoProject.isThing(selectedNode)) {
                                        componentMenuItemActionPerformedClick(e);
                                    }
                            }
                            });
                            createNewController.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent e) {
                                    DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) arvoreCoisa.getLastSelectedPathComponent();
                                    if (novoProject.isThing(selectedNode)) {
                                        controllerMenuItemActionPerformedClick(e);
                                    }
                                }
                            });
                            popupMenu.add(createNewComponent);
                            popupMenu.add(createNewController);
                            arvoreCoisa.setComponentPopupMenu(popupMenu);
                        break;
                        case COMPONENT:
                            arvoreCoisa.remove(popupMenu);
                            createNewPort.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) arvoreCoisa.getLastSelectedPathComponent();
                                if (novoProject.isComponent(selectedNode)) {
                                    portaMenuItemActionPerformedClick(e);
                                }
                            }});
                            createNewTopic.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) arvoreCoisa.getLastSelectedPathComponent();
                                if (novoProject.isComponent(selectedNode)) {
                                    topicMenuItemActionPerformedClick(e);
                                }
                            }});
                            popupMenu.add(createNewPort);
                            popupMenu.add(createNewTopic);
                            arvoreCoisa.setComponentPopupMenu(popupMenu);
                            arvoreCoisa.getComponentPopupMenu();
                        break;
                        case CONTROLLER:
                            arvoreCoisa.remove(popupMenu);
                            createNewPort.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) arvoreCoisa.getLastSelectedPathComponent();
                                if (novoProject.isController(selectedNode)) {
                                    portaMenuItemActionPerformedClick(e);
                                }
                            }});
                            popupMenu.add(createNewPort);
                            arvoreCoisa.setComponentPopupMenu(popupMenu);
                            arvoreCoisa.getComponentPopupMenu();
                        break;
                        case PROJECT:
                            arvoreCoisa.remove(popupMenu);
                            createNewThing.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) arvoreCoisa.getLastSelectedPathComponent();
                                if (novoProject.isProject(selectedNode) || novoProject.isThing(selectedNode)) {
                                    thingMenuItemActionPerformedClick(e);
                                }
                            }
                            });
                            popupMenu.add(createNewThing);
                            arvoreCoisa.setComponentPopupMenu(popupMenu);
                            arvoreCoisa.getComponentPopupMenu();
                        break;
                        case PROTOCOL:
                            arvoreCoisa.remove(popupMenu);
                            editProtocol.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) arvoreCoisa.getLastSelectedPathComponent();
                                if (novoProject.isProtocol(selectedNode)) {
                                    protocolMenuItemActionPerformedClick(e);
                                }
                            }});
                            popupMenu.add(editProtocol);
                            arvoreCoisa.setComponentPopupMenu(popupMenu);
                            arvoreCoisa.getComponentPopupMenu();
                        break;
                        case SERVER:
                            arvoreCoisa.remove(popupMenu);
                            editServer.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) arvoreCoisa.getLastSelectedPathComponent();
                                if (novoProject.isServer(selectedNode)) {
                                    serverMenuItemActionPerformedClick(e);
                                }
                            }});
                            popupMenu.add(editServer);
                            arvoreCoisa.setComponentPopupMenu(popupMenu);
                            arvoreCoisa.getComponentPopupMenu();
                        break;
                        case TOPIC:
                        break;
                        default:
                        break;
                    }
                }
        }});
    }
    
    private void thingMenuItemActionPerformedClick(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
        ThingPage tela = new ThingPage(arvoreCoisa, thing, project);
        tela.setVisible(true);
    }               

    private void controllerMenuItemActionPerformedClick(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
        ControllerPage tela = new ControllerPage(arvoreCoisa,project);
        tela.setVisible(true);
    }                                              

    private void portaMenuItemActionPerformedClick(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
        PortPage tela = new PortPage(arvoreCoisa,project);
        tela.setVisible(true);
    }                                              

    private void topicMenuItemActionPerformedClick(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
        TopicPage tela = new TopicPage(topic, arvoreCoisa, project);
        tela.setVisible(true);
    }                                              

    private void btnCancelActionPerformedClick(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
        super.dispose();
    }                                         

    private void protocolMenuItemActionPerformedClick(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
        ProtocolPage tela = new ProtocolPage(arvoreCoisa,project);
        tela.setVisible(true);
    }                                              

    private void serverMenuItemActionPerformedClick(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
        ServerPage tela = new ServerPage(arvoreCoisa,project);
        tela.setVisible(true);
    }
    

    private void componentMenuItemActionPerformedClick(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
        ComponentPage tela = new ComponentPage(arvoreCoisa, project);
        tela.setVisible(true);
    }
     
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainPage().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem aboutMenuItem;
    private javax.swing.JTree arvoreCoisa;
    private javax.swing.JMenuItem contentMenuItem;
    private javax.swing.JMenuItem componentMenuItem;
    private javax.swing.JMenuItem portMenuItem;
    private javax.swing.JMenuItem controllerMenuItem;
    private javax.swing.JMenuItem thingMenuItem;
    private javax.swing.JDesktopPane desktopPane;
    private javax.swing.JMenu projectMenu;
    private javax.swing.JMenuItem exitMenuItem;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenu helpMenu;
    private javax.swing.JMenuItem topicMenuItem;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem openMenuItem;
    private javax.swing.JMenuItem openProjectMenuItem;
    private javax.swing.JMenuItem protocolPage;
    private javax.swing.JMenuItem saveAsMenuItem;
    private javax.swing.JMenuItem serverMenuItem;
    // End of variables declaration//GEN-END:variables

}
